<?php
namespace backend\controllers;

use common\models\AuthAssignment;
use common\models\AuthItem;
use common\models\AuthItemChild;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\AdminLoginForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    public function actionIndex()
    {
        //权限数据表
        $permissions  = [];
        $id = Yii::$app->user->identity->getId();
        $roles  = AuthAssignment::find()->where(['user_id'=>$id])->all();
        foreach ($roles as $k => $v){
            $childs = AuthItemChild::find()->select('child')->where(['parent'=>$v->item_name])->all();
            foreach ($childs as $k => $v){
                $des = AuthItem::find()->select('description')->where(['name'=>$v->child])->one();
                $permissions[$v->child] = $des->description;
            }
        }
        $permissions = array_unique($permissions);
        $arr['text_arr'] = $permissions;
        $list = [];
        $str2 = "index";
        foreach ($arr['text_arr'] as $k => $v){
            if( strrchr($k,$str2) == $str2 ){
                $list[$k ] = $v;
            }

        }

        $arr['text_arr'] = $list;



        return $this->render('index',$arr);
    }

    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new AdminLoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();//登录成功，回到登录前的页面
        } else {
            return $this->render('login', [
                'model' => $model,
            ]); //登录失败，登录页展示错误，让用户填写正确的用户名和密码
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}
